﻿<?php

require_once "lib/logger.class.php";
require_once "models/m-user.class.php";
require_once "models/m-customer.class.php";
require_once "models/m-job.class.php";
require_once "models/m-region.class.php";
require_once "views/v-orders.class.php";
require_once "views/v-user.class.php";
require_once "views/v-customer.class.php";
require_once "views/v-job.class.php";
require_once "views/v-region.class.php";
require_once "views/v-menu.class.php";
require_once "views/v-frame.class.php";

class cMain
{
	private $user;

	public function __construct()
	{
	}

	public function Exec()
	{

		$title = "Рабочее место";
		$menu = "";
		$body = "";

		$this->user = new mUser();


		if($this->Auth())
		{
			if(isset($_GET['logout']))
			{
				$this->user->Logout();
				header('location: index.php');
			}
			else
			{
				// $is_ajax = isset($_GET["ajax"]) ? (strtolower($_GET["ajax"]) == "y") : false;
				// if($is_ajax)
				if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
					header('Content-type: application/json');
					$this->AnswerOnAjax();
				}
				else
				{
					$this->ShowPage();
				}

			}
		}
		else
		{
			$title = "Авторизация";
			$body = vUser::LoginForm();
			echo vFrame::Build($title, $menu, $body);
		}
	}

	public function Auth()
	{
		if(isset($_POST['email']))
		{
			$is_login = $this->user->Login();
			if($is_login)
			{
				header('location: index.php');
			}
			return $is_login;
		}
		else
		{
			return $this->user->CheckSession();
		}
	}

	public function ShowPage()
	{
		// echo '<!DOCTYPE HTML>';

		$title = "Сделай сам!";
		$menu = "";
		$body = "";

		$page_code = isset($_GET["page"]) ? $_GET["page"] : null;
		$page_act = isset($_GET["act"]) ? $_GET["act"] : null;

		$menu = vMenu::Generate($this->user->Pages, $page_code, $title);

		$is_owner = $this->user->RoleExists('owner');

		if($this->user->IsPageAllowed($page_code))
		{
			switch ($page_code) {
				case 'orders':
					vFrame::AddScript("orders");
					$body = vOrder::FoundByPhone();
					break;
				
				case 'customers':
					$data = new mCustomer();
					vFrame::AddScript("customers");
					$body = vCustomer::Generate($data->rows, $is_owner);
					break;
				
				case 'workers':
					vFrame::AddScript("workers");
					$body = vUser::WorkersTable($this->user->LoadUsersByRole('work'), $is_owner);
					break;
				
				case 'jobs':
					$data = new mJob();
					Logger::log('control', print_r($data, true));
					vFrame::AddScript("jobs");
					$body = vJob::Generate($data->rows, $is_owner);
					break;
				
				case 'regions':
					$data = new mRegion();
					vFrame::AddScript("regions");
					$body = vRegion::Generate($data->rows, $is_owner);
					break;
				
				default:
					$body = "";
					break;
			}


			echo vFrame::Build($title, $menu, $body);
		}
		else
		{
			echo vFrame::BuildWarning($title, $menu, 'Ваш IP-адрес зафиксирован. Ошибка будет исследована.');
		}
	}

	public function AnswerOnAjax()
	{
		$xml = file_get_contents('php://input');
		Logger::log('AnswerOnAjax', print_r($xml, true));
		$req = new SimpleXMLElement($xml);

		$ans = array();
		array_push($ans, array("error", "unkonwn command"));

		$obj = $req["obj"];
		$act = $req["act"];
		$val = $req["val"];
		switch($obj){
			case "job":
				switch($act){
					case "edit":
						try
						{
							foreach ($req->job as $job) {
								// Logger::log('AnswerOnAjax 2', print_r($job, true));
								mJob::Edit((string)$job["id"], (string)$job["title"]);
							}
						}
						catch(Exception $ex)
						{
							$err = array('error' => $ex->getMessage());
							array_push($ans, $err);
							Logger::log('AnswerOnAjax job.edit', print_r($ex, true));
						}
						break;
				}
				break;

			case "customer":
				switch($act)
				{
					// <req obj="customer" act="find_by_phone" val="123" />
					case "find_by_phone":
						$cust = new mCustomer();
						$ans = $cust->GetCustomersByPhonePattern($val);

						break;
				}
				break;
		}

		Logger::log("ajax prepared answer:", print_r($ans, true));
		$json = json_encode($ans);
		Logger::log("ajax json answer:", $json);

		header('Content-type: application/json');
		echo $json;
	}
}